package cn.yunyichina.reservation.common.spring;

import cn.yunyichina.reservation.constant.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * Created by Lullaby on 2016/8/22.
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /**
     * 400 - Bad Request
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public HttpResponse handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        logger.error("Bad Request", e);
        return new HttpResponse().failure("Bad Request");
    }

    /**
     * 404 - Not Found
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public HttpResponse handleException(NoHandlerFoundException e) {
        logger.error("Not Found", e);
        return new HttpResponse().failure("Not Found");
    }

    /**
     * 405 - Method Not Allowed
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public HttpResponse handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("Method Not Allowed", e);
        return new HttpResponse().failure("Method Not Allowed");
    }

    /**
     * 415 - Unsupported Media Type
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public HttpResponse handleHttpMediaTypeNotSupportedException(Exception e) {
        logger.error("Unsupported Media Type", e);
        return new HttpResponse().failure("Unsupported Media Type");
    }

    /**
     * 500 - Internal Server Error
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public HttpResponse handleException(Exception e) {
        logger.error("Internal Server Error", e);
        return new HttpResponse().failure("Internal Server Error");
    }

}
